#pragma once
#include <iostream>
#include <string>
#include <functional>
#include <cstring>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include "InetAddr.hpp"
#include "nocopy.hpp"
#include "Log.hpp"

using namespace log_ns;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR
};

using command_service_t = std::function<void(int sockfd, InetAddr addr)>;

class TcpServer : public nocopy
{
public:
    TcpServer(uint16_t localport, command_service_t service) 
    : _sockfd(-1), 
    _localport(localport),
    _isrunning(false),
    _service(service)
    {
    }

    void Init()
    {
        extern int errno;
        // 1. 创建 socket 文件描述符
        _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "sockfd error\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "sockfd create sucess, sockfd: %d\n", _sockfd);

        // 2. 绑定端口号
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_localport);
        local.sin_addr.s_addr = INADDR_ANY;

        if (::bind(_sockfd, (sockaddr *)&local, sizeof(local)) < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "socket bind sucess\n");

        // 3. listen
        if (::listen(_sockfd, 8) < 0)
        {
            LOG(FATAL, "listen error, errno %d\n", errno);
            exit(LISTEN_ERROR);
        }
        LOG(DEBUG, "listen sucess\n");
    }

    struct ThreadDate
    {
        int _sockfd;
        TcpServer *_self;
        InetAddr _addr;
        ThreadDate(int sockfd, TcpServer *self, const InetAddr &addr)
            : _sockfd(sockfd), _self(self), _addr(addr)
        {
        }
    };

    static void *Execute(void *arg)
    {
        pthread_detach(pthread_self());
        ThreadDate *td = static_cast<ThreadDate *>(arg);
        td->_self->_service(td->_sockfd, td->_addr);
        delete td;
        return nullptr;
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            sockaddr_in client;
            socklen_t len = sizeof(client);
            int sockfd = ::accept(_sockfd, (sockaddr *)&client, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
                continue;
            }
            InetAddr addr(client);
            LOG(INFO, "get a new link, client info : %s, sockfd is : %d\n",
                addr.addrStr().c_str(), sockfd);

            pthread_t tid;
            pthread_create(&tid, nullptr, Execute,
                           new ThreadDate(sockfd, this, addr));
        }
        _isrunning = false;
    }

    ~TcpServer()
    {
        if (_sockfd > 0)
            ::close(_sockfd);
    }

private:
    int _sockfd;
    uint16_t _localport;
    bool _isrunning;
    command_service_t _service;
};